#include "../../include/server/SearchEngineServer.h"
#include <iostream>
#include <unistd.h>
#include <memory>
#include "../../include/CacheManager.h"
using std::cout;
using std::endl;
using std::unique_ptr;

SearchEngineServer::
SearchEngineServer(size_t threadNum,size_t queSize,const string &ip,unsigned short port)
:_pool(threadNum,queSize)
,_server(ip,port)
{

}

SearchEngineServer::~SearchEngineServer()
{

}

void SearchEngineServer::start(){
    _pool.start();
    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&SearchEngineServer::onNewConnection, this, _1)
                               , std::bind(&SearchEngineServer::onMessage, this, _1)
                               , std::bind(&SearchEngineServer::onClose, this, _1));
    _server.start();
}

void SearchEngineServer::stop(){
    _pool.stop();
    _server.stop();
}

void SearchEngineServer::onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected!" << endl;
}

void SearchEngineServer::onMessage(const TcpConnectionPtr &con)
{
    string msg = con->receive();
    cout << ">>recv client msg = " << msg << endl;

    using namespace std::placeholders;
    _pool.addTask(std::bind(&SearchEngineServer::doTaskThread,this,con,msg));
}

void SearchEngineServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed!" << endl;
}

void SearchEngineServer::doTaskThread(const TcpConnectionPtr &conn,string &msg){
    CacheManager *manager = CacheManager::getInstance();
    manager->initCache(4, string());
    LRUCache &LruCache = manager->getCache(atoi(name));
    auto msgJson = json::parse(msg);
    string message;
    string messageId = msgJson["messageId"];
    string messageS = msgJson["message"];
    if (messageId == "1")
    {
        if(LruCache.search(messageS))
        {
            cout << "thread name: " << name << endl;
            LogInfo("走cache缓存,用户查询%s", messageS.c_str());
            string ans;
            ans = LruCache.get(messageS);
            json msgJson;
            msgJson["messageId"] = "100";
            msgJson["message"] = ans;
            message = msgJson.dump();
            
        }
        else
        {
            cout << "thread name: " << name << endl;
            ProtocolParser protocolParser(msg);
            message=protocolParser.doParse();
            LruCache.put(messageS, message);
        }
    }
    else
    {
        cout << "thread name: " << name << endl;
        ProtocolParser protocolParser(msg);
        message=protocolParser.doParse();
    }
    
    conn->sendInLoop(message);
}
